package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecParam;
import com.leyou.item.entity.SpuDetail;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.service.SpecParamService;
import com.leyou.item.service.SpuDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author BaiZY on 2020/8/26.
 * @version 1.0
 */
@Service
public class SpuDetailServiceImpl extends ServiceImpl<SpuDetailMapper, SpuDetail> implements SpuDetailService {
    @Autowired
    private SpecParamService specParamService;


    @Override
    public List<SpecParamDTO> querySpecValues(Long spuId, Boolean searching) {
        //1.获取spudetail
        SpuDetail spuDetail = getById(spuId);
        //2.获取specification
        String specification = spuDetail.getSpecification();
        //3.将Json字符创装换成Map
        Map<Long, Object> specMap = JsonUtils.nativeRead(specification, new TypeReference<Map<Long, Object>>() {
        });

        //4.取出Map的key转换成list集合
        ArrayList<Long> specParamsIds = new ArrayList<>(specMap.keySet());

        //5.查询specParam
        List<SpecParam> specParams = specParamService.listByIds(specParamsIds);

        //转换
        List<SpecParamDTO> specParamDTOList = SpecParamDTO.convertEntityList(specParams);

        //找到param的value，并存储
        for (SpecParamDTO specParamDTO : specParamDTOList) {
            specParamDTO.setValue(specMap.get(specParamDTO.getId()));
        }
        return specParamDTOList;
    }
}
